<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formInline" class="search-form">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="formInline.id"
          placeholder="输入设备ProductKey"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button size="small" icon="el-icon-plus" @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="$store.state.loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column type="index" width="60"> </el-table-column>
      <el-table-column sortable prop="id" label="ProductKey" width="200">
      </el-table-column>
      <el-table-column sortable prop="name" label="产品名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="cateName" label="品类" width="100">
      </el-table-column>
      <el-table-column sortable prop="createAt" label="修改时间" width="150">
        <template slot-scope="scope">
          <div>{{ scope.row.createAt | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            @click="handleEditThingModel(scope.$index, scope.row)"
            >物模型</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :data="formInline" @onPagePaging="search"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="40%"
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="ProductKey" prop="id">
          <el-input
            size="small"
            v-model="editForm.id"
            auto-complete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="节点类型" prop="nodeType">
          <el-radio-group v-model="editForm.nodeType">
            <el-radio :label="0">网关设备</el-radio>
            <el-radio :label="1">网关子设备</el-radio>
            <el-radio :label="2">直连设备</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="品类" prop="category">
          <el-select
            size="small"
            v-model="editForm.category"
            placeholder="请选择品类"
          >
            <el-option
              v-for="cate in categories"
              :label="cate.name"
              :value="cate.id"
              :key="cate.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="透传设备" prop="transparent">
          <el-radio-group v-model="editForm.transparent">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="产品图片" prop="pic">
          <div class="pic-upload">
            <img
              v-if="editForm.img && !showUpload"
              :src="editForm.img"
              class="avatar"
            />
            <el-upload
              v-if="showUpload"
              class="upload-demo"
              drag
              :action="getUploadAction()"
              :headers="getAuthHeaders()"
              :on-success="uploadSuccess"
              multiple
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <el-button v-if="!showUpload" size="mini" @click="onShowUpload"
              >上传</el-button
            >
            <el-button v-if="showUpload" size="mini" @click="onHideUpload"
              >取消</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="$store.state.loading"
          class="title"
          @click="submitEditForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 编辑物模型 -->
    <el-dialog
      title="产品物模型"
      :visible.sync="editThingModelFormVisible"
      width="70%"
      @click="closeDialog"
      class="thing-model-dlg"
      top="2vh"
    >
      <ThingModel :productKey="currentProductKey"></ThingModel>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
import {
  CategoryList,
  ProductList,
  ProductSave,
  ThingModelSave,
} from "../../api/productApi";
import Pagination from "../../components/Pagination";
import ThingModel from "./ThingModel.vue";
export default {
  data() {
    return {
      loading: false,
      editFormVisible: false,
      editThingModelFormVisible: false,
      title: "添加",
      editForm: {
        id: "",
        name: "",
        category: "",
        nodeType: 0,
        transparent: false,
      },
      thingModelForm: {},
      currentProductKey: "",
      categories: [],
      // rules表单验证
      rules: {},
      showUpload: false,
      formInline: {
        page: 1,
        size: 10,
        total: 0,
      },
      listData: [],
    };
  },
  components: {
    Pagination,
    ThingModel,
  },
  created() {
    this.getdata(this.formInline);
  },
  methods: {
    getdata(parameter) {
      CategoryList(parameter).then((res) => {
        this.categories = res;
        let cateMap = {};
        this.categories.forEach((c) => {
          cateMap[c.id] = c.name;
        });

        ProductList(parameter).then((res) => {
          res.data.forEach((p) => {
            p.cateName = cateMap[p.category];
          });

          this.listData = res.data;
          this.formInline.total = res.total;
        });
      });
    },
    search() {
      this.getdata(this.formInline);
    },
    randomString(len) {
      len = len || 32;
      var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      var maxPos = $chars.length;
      var pwd = "";
      for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    onShowUpload() {
      this.showUpload = true;
    },
    onHideUpload() {
      this.showUpload = false;
    },
    getUploadAction() {
      return (
        process.env.VUE_APP_API_BASE_PATH +
        "/product/uploadImg/" +
        this.editForm.id
      );
    },
    getAuthHeaders() {
      return {
        token: Vue.prototype.accessToken,
      };
    },
    uploadSuccess(response) {
      this.editForm.img = response;
      this.showUpload = false;
    },
    handleEdit(index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.showUpload = false;
        this.title = "编辑产品";
        this.editForm.id = row.id;
        this.editForm.name = row.name;
        this.editForm.category = row.category;
        this.editForm.nodeType = row.nodeType;
        this.editForm.img = row.img;
      } else {
        this.title = "添加产品";
        this.editForm.id = this.randomString(16);
        this.editForm.name = "";
        this.editForm.category = "";
        this.editForm.nodeType = 0;
      }
    },
    //显示编辑界面
    handleEditThingModel(index, row) {
      this.editThingModelFormVisible = true;
      let that = this;
      setTimeout(function () {
        that.currentProductKey = "";
      }, 100);
      setTimeout(function () {
        that.currentProductKey = row.id;
      }, 110);
    },
    submitEditForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          ProductSave(this.editForm).then(
            () => {
              this.editFormVisible = false;
              this.$message({
                type: "success",
                message: "保存成功！",
              });
              this.search();
            },
            () => {
              this.editFormVisible = false;
            }
          );
        }
      });
    },
    // 保存物模型
    submitThingModelForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          ThingModelSave({
            productKey: this.thingModelForm.productKey,
            model: JSON.stringify(this.thingModelForm.model),
          }).then(
            () => {
              this.editThingModelFormVisible = false;
              this.$message({
                type: "success",
                message: "保存成功！",
              });
            },
            () => {
              this.editThingModelFormVisible = false;
            }
          );
        } else {
          return false;
        }
      });
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editThingModelFormVisible = false;
      this.editFormVisible = false;
    },
  },
};
</script>

<style>
.jsoneditor-vue {
  height: 500px !important;
}

.thing-model-dlg .el-dialog__body {
  padding: 0 0;
}
</style>

<style scoped>
.userRole {
  width: 100%;
}

.pic-upload {
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 70%;
}
</style>
